package com.qd.streaming;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.os.Environment;
import android.util.Log;

public class MediaFile implements Runnable {
	boolean running = false;
	FileOutputStream fos = null;
	FileInputStream fis = null;
	InputStream is = null;
	private Thread t;
	public MediaFile() throws IOException {
		File file = Environment.getExternalStorageDirectory();
		String path = file.getAbsolutePath() + "/download/video/"+Long.toString(System.currentTimeMillis()) + ".mp4";
		File mf = new File(path);
		fos = new FileOutputStream(mf);
		fis = new FileInputStream(mf);
	}
	
	public FileDescriptor getFileDescriptor(){
		try {
			return fos.getFD();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	public InputStream getInputStream(){
		return this.fis;
	}
	
	
	public void setInputStream(InputStream is) {
		this.is = is;
	}
	
	public void start() throws IOException {
		if (!running) {
			running = true;
			//t = new Thread(this);
			//t.start();
		}
	}

	public void stop() {
		try {
			fos.close();
		} catch (IOException ignore) {}
		running = false;
	}

	public void run() {
		// Each packet we send has a two byte long header (See section 5.1 of RFC 4629)
		try { 
			int buf = 0;
			while (running) {
				while((buf=is.read()) != -1) {
		            fos.write(buf); //☆
		         }
			}
		} catch (IOException e) {
			running = false;
			e.printStackTrace();
		}
	}
}
